import { reqCartList, removeCartList, changeCartCheck } from "@/api/cart";

const state = {
  getCartList: [] // 获取购物车列表数据
}
const mutations = {
  a() {},
  getCartFn(state, cart) {
    state.getCartList = cart
  }
}
const actions = {
  // 商品的选中状态随着全选的状态而改变
  changeCheckAll({dispatch, state}, isChecked) {
    let PromiseAll = []
    state.getCartList[0].cartInfoList.forEach(item => {
      let promise = dispatch('changeCartCheckFn',{
        skuID: item.id,
        isChecked
      })
      PromiseAll.push(promise)
    })
    return Promise.all(PromiseAll)
  },
  // 删除所有选中的商品
  delAllCartFn({dispatch, state}) {
    // console.log(context); 打印出来actions所有方法模块，我们需要dispatch调用删除单个的方法和state拿到数据的方法
    // 拿到存放所有商品数据的数组进行遍历，把每一项的id传过去
    let PromiseAll = []
    state.getCartList[0].cartInfoList.forEach(item => {
      let res = item.isChecked === 1 ? dispatch('delCart', item.id):''
      PromiseAll.push(res)
    })
    return Promise.all(PromiseAll)
  },
  // 修改商品选中状态
  async changeCartCheckFn({commit}, {skuID, isChecked}) {
    await changeCartCheck(skuID, isChecked)
    commit('a')
  },
  // 删除购物车的数据的函数
  async delCart({commit}, id) {
    await removeCartList(id)
    commit('a')
  },
  async getCartList({commit}){
    let res = await reqCartList()
    console.log(res);
    if (res.data.code === 200) {
      commit('getCartFn', res.data.data)
    }
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}